package service

import (
	"time"

	"github.com/pkg/errors"
	"github.com/tebeka/selenium"
)

type Form struct {
}

func (s Form) Start() {
	driver := SetupDriver()
	defer server.Stop()
	defer driver.Quit()

	s.submit(driver)
}

func (s Form) submit(driver selenium.WebDriver) error {
	files := []string{
		`D:\phpstudy_pro\WWW\yahoo\file\QQ20241013-193446(1).jpg`,
		`D:\phpstudy_pro\WWW\yahoo\file\QQ20241013-193504(1).jpg`,
	}

	//打开列表页
	err := driver.Get("https://auctions.yahoo.co.jp/sell/jp/show/submit?category=2084047648")
	if err != nil {
		return errors.Wrap(err, "打开表单页失败")
	}

	//轮询等待页面加载完成
	var image selenium.WebElement
	err = driver.WaitWithTimeout(func(wd selenium.WebDriver) (bool, error) {
		image, err = driver.FindElement(selenium.ByID, "#selectFileMultiple")
		//元素未找到，继续等待
		if err != nil {
			return false, nil
		}
		return true, nil
	}, time.Second*60)
	if err != nil {
		return errors.Wrap(err, "表单页面加载超时")
	}

	for _, file := range files {
		//选择文件
		err = image.SendKeys(file)
		if err != nil {
			return errors.Wrap(err, "上传文件失败")
		}

	}

	//获取input name=".crumb"的值
	//获取input name="imgUploadUrl"的值
	//参数
	//files[0]: (binary)
	//.crumb: faadd1ab12557796d217a581050b700818bf69548964da9866444bb7ef5f2118

	//返回结果images[0].url，把值填入ImageFullPath1，ImageFullPath2，ImageFullPath3的input中

	return nil
}
